//package com.dn.dngateway;
//
//import cn.hutool.core.collection.CollectionUtil;
//import cn.hutool.core.util.StrUtil;
//import com.dn.dnclientsdk.utils.SignUtils;
//import com.dn.dngateway.model.GatewayLog;
//import com.google.gson.Gson;
//import lombok.extern.slf4j.Slf4j;
//import org.reactivestreams.Publisher;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.cloud.gateway.route.Route;
//import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.core.io.buffer.DataBufferFactory;
//import org.springframework.core.io.buffer.DataBufferUtils;
//import org.springframework.core.io.buffer.DefaultDataBufferFactory;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
//import org.springframework.stereotype.Component;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.server.ServerWebExchange;
//import org.springframework.web.util.UriComponentsBuilder;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.nio.charset.StandardCharsets;
//import java.util.Arrays;
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//
//@Slf4j
//@Component
//public class CustomGlobalFilterNewDemo implements GlobalFilter, Ordered {
//
//    /**
//     * ip 白名单
//     */
//    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        //2.请求日志
//        ServerHttpRequest request = exchange.getRequest();
//        log.info("请求标识：" + request.getId());
//        log.info("请求路径：" + request.getPath().value());
//        log.info("请求方法：" + request.getMethod());
//        log.info("请求参数：" + request.getQueryParams());
//        log.info("请求来源：" + request.getRemoteAddress().getHostString());
//        log.info("请求来源：" + request.getLocalAddress().getHostString());
//        String sourceAddress = request.getLocalAddress().getHostString();
//
//        ServerHttpResponse response = exchange.getResponse();
//        GatewayLog gatewayLog = new GatewayLog();
//        // 设置日志请求信息
//        setLogInfo(exchange, request, gatewayLog);
//
//        // 判断 黑白名单
//        if (!IP_WHITE_LIST.contains(sourceAddress)) {
//            // 拦截, 禁止访问，设置状态码
//            return handleNoAuth(response);
//        }
//        // 用户鉴权(判断ak、sk是否合法)
//        String accessKey = request.getHeaders().getFirst("accessKey");
//        String nonce = request.getHeaders().getFirst("nonce");
//        String body = request.getHeaders().getFirst("body");
//        String timestamp = request.getHeaders().getFirst("timestamp");
//        String sign = request.getHeaders().getFirst("sign");
//        if (!"dn".equals(accessKey)) {
//            return handleNoAuth(response);
//        }
//        if (Long.parseLong(nonce) > 10000) {
//            return handleNoAuth(response);
//        }
//        boolean overtime = ((System.currentTimeMillis() / 1000) - Long.parseLong(timestamp)) > (5 * 60);
//        if (overtime) {
//            return handleNoAuth(response);
//        }
//        String secretKey = "jt";
//        String serverSign = SignUtils.genSign(body, secretKey);
//        if (!serverSign.equals(sign)) {
//            return handleNoAuth(response);
//        }
//        // 请求的模拟接口是否存在? todo: 需要远程调用
//        // 请求转发,调用模拟接口 todo: 需要远程调用
//
//        //响应日志
//        log.info("响应：" + response.getStatusCode());
//        // 参考：https://www.toutiao.com/article/7091439811768205835/?wid=1710899442480
//        return writeBasicLog(exchange, chain, gatewayLog);
//        //调用成功,接口调用次数+1  todo: 需要远程调用，方法
////        if (response.getStatusCode() != HttpStatus.OK) {
////            log.info("调用成功");
////        } else {    //.调用失败,返回一个规范的错误码
////            return handleInvokeError(response);
////        }
////        log.info("custom global filter");
////        return chain.filter(exchange);
//    }
//
//
//
//    @Override
//    public int getOrder() {
//        return -1;
//    }
//
//
//    /**
//     * 设置请求日志信息
//     * @param exchange
//     * @param request
//     * @param gatewayLog
//     */
//    private void setLogInfo(ServerWebExchange exchange, ServerHttpRequest request, GatewayLog gatewayLog) {
//        String ipAddress = request.getLocalAddress().getHostString();
//        // 请求路径
//        String requestPath = request.getPath().pathWithinApplication().value();
//        Route route = getGatewayRoute(exchange);
//        // 协议
//        gatewayLog.setSchema(request.getURI().getScheme());
//        // 请求方法
//        gatewayLog.setRequestMethod(request.getMethodValue());
//        // 请求路径
//        gatewayLog.setRequestPath(requestPath);
//        // 访问实例
//        gatewayLog.setTargetServer(route.getId());
//        // 请求时间
//        gatewayLog.setRequestTime(new Date());
//        // 请求ip
//        gatewayLog.setIp(ipAddress);
//
//        MediaType mediaType = request.getHeaders().getContentType();
//        // 请求数据类型
//        gatewayLog.setRequestContentType(mediaType.getType() + "/" + mediaType.getSubtype());
//    }
//
//    /**
//     * 记录日志
//     * @param exchange
//     * @param chain
//     * @param accessLog
//     * @return
//     * 参考：https://www.toutiao.com/article/7091439811768205835/?wid=1710899442480
//     */
//    private Mono<Void> writeBasicLog(ServerWebExchange exchange, GatewayFilterChain chain, GatewayLog accessLog) {
//
//        return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
//            DataBufferUtils.retain(dataBuffer);
//            final Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
//            final ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
//                @Override
//                public Flux<DataBuffer> getBody() {
//                    return cachedFlux;
//                }
//                @Override
//                public MultiValueMap<String, String> getQueryParams() {
//                    return UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).build().getQueryParams();
//                }
//            };
//            StringBuilder builder = new StringBuilder();
//            MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
//            if (CollectionUtil.isNotEmpty(queryParams)) {
//                for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
////                    builder.append(entry.getKey()).append("=").append(StrUtil.join(entry.getValue(), ","));
//                    builder.append(entry.getKey()).append("=").append(StrUtil.join(",", entry.getValue()));
//                }
//            }
//            accessLog.setRequestBody(builder.toString());
//            //获取响应体
//            ServerHttpResponseDecorator decoratedResponse = recordResponseLog(exchange, accessLog);
//            return chain.filter(exchange.mutate().request(mutatedRequest).response(decoratedResponse).build())
//                    .then(Mono.fromRunnable(() -> {
//                        // 打印日志
////                        writeAccessLog(accessLog);
//                        Gson gson = new Gson();
//                        String json = gson.toJson(accessLog);
//                        System.out.println("json: " + json);
//                    }));
//        });
//    }
//
//
//    /**
//     * 记录响应日志
//     * 通过 DataBufferFactory 解决响应体分段传输问题。
//     */
//    private ServerHttpResponseDecorator recordResponseLog(ServerWebExchange exchange, GatewayLog gatewayLog) {
//        ServerHttpResponse response = exchange.getResponse();
//        DataBufferFactory bufferFactory = response.bufferFactory();
//
//        return new ServerHttpResponseDecorator(response) {
//            @Override
//            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
//                if (body instanceof Flux) {
//                    Date responseTime = new Date();
//                    gatewayLog.setResponseTime(responseTime);
//                    // 计算执行时间
//                    long executeTime = (responseTime.getTime() - gatewayLog.getRequestTime().getTime());
//
//                    gatewayLog.setExecuteTime(executeTime);
//
//                    // 获取响应类型，如果是 json 就打印
//                    String originalResponseContentType = exchange.getAttribute(ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
////                    log.info("originalResponseContentType =========== " + originalResponseContentType);
//
//                    gatewayLog.setResponseContentType(originalResponseContentType);
//
//                    gatewayLog.setCode(this.getStatusCode().value());
//
////                    if (ObjectUtils.equals(this.getStatusCode(), HttpStatus.OK)
////                            && !StringUtil.isNullOrEmpty(originalResponseContentType)
////                            && originalResponseContentType.contains("application/json")) {
//
//                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
//                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
//
//                        // 合并多个流集合，解决返回体分段传输
//                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
//                        DataBuffer join = dataBufferFactory.join(dataBuffers);
//                        byte[] content = new byte[join.readableByteCount()];
//                        join.read(content);
//
//                        // 释放掉内存
//                        DataBufferUtils.release(join);
//                        String responseResult = new String(content, StandardCharsets.UTF_8);
////                            log.info("responseResult =========== " + responseResult);
//                        gatewayLog.setResponseData(responseResult);
//
//                        return bufferFactory.wrap(content);
//                    }));
//                }
////                }
//
//                // if body is not a flux. never got there.
//                return super.writeWith(body);
//            }
//        };
//    }
//
//
//    /**
//     * 获取网关路由
//     * @param exchange
//     * @return
//     */
//    private Route getGatewayRoute(ServerWebExchange exchange) {
//        return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
//    }
//
//
//    /**
//     * 没权限处理
//     *
//     * @param response
//     * @return
//     */
//    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
//        response.setStatusCode(HttpStatus.FORBIDDEN);
//        return response.setComplete();
//    }
//
//    /**
//     * 调用接口失败
//     *
//     * @param response
//     * @return
//     */
//    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
//        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
//        return response.setComplete();
//    }
//}